package com.csjbot.blackgaga.model.http.product;

import android.content.Context;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.Log;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.csjbot.blackgaga.BaseApplication;
import com.csjbot.blackgaga.R;
import com.csjbot.blackgaga.cart.entity.RobotMenuListBean;
import com.csjbot.blackgaga.cart.entity.RobotSpBean;
import com.csjbot.blackgaga.cart.entity.RobotSpListBean;
import com.csjbot.blackgaga.cart.pactivity.evaluate.AnswerResponse;
import com.csjbot.blackgaga.global.Constants;
import com.csjbot.blackgaga.model.http.bean.AdInfo;
import com.csjbot.blackgaga.model.http.bean.PayResponse;
import com.csjbot.blackgaga.model.http.bean.PayResult;
import com.csjbot.blackgaga.model.http.bean.ProductInfo;
import com.csjbot.blackgaga.util.BlackgagaLogger;
import com.csjbot.blackgaga.util.ConfInfoUtil;
import com.csjbot.blackgaga.util.FileUtil;
import com.csjbot.blackgaga.util.SharedKey;
import com.csjbot.blackgaga.util.SharedPreUtil;
import com.csjbot.coshandler.log.Csjlogger;
import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * @author xiasuhuei321
 *         Changed by jingwc on 2017/9/18.
 */

public class ProductProxy implements IProduct {

    private IProduct iProduct;

    private String TAG = this.getClass().getSimpleName();

    private Integer downloadCount = 0;

    private Integer alreadyCount = 0;

    public static final String PRODUCT_IMG_PATH = Environment.getExternalStorageDirectory() +
            File.separator + "blackgaga" + File.separator + "product_image" + File.separator;

    public static String SN = "040017470018";

    /**
     * 是正常的更新数据还是强制同步数据
     */
    public static boolean ISUPDATA;

    /**
     * 获取当前sp下的图片数量
     */
    private Integer SP_SIZE = 0;

    /**
     * 确保当前不是一个下载地址，多个menu下载对应的sp
     */
    private static Integer NEED_LOAD = 0;


    private Integer isLoadNum = 0;


    /**
     * 已经下载的图片
     */
    private int ARLEADY_DOWNLOAD = 0;

    /**
     * 下载图片和视频资源有多少
     */
    private static Integer NEED_LOAD_MEDIA = 0;


    /**
     * 需要更新数据的列表
     */
    private static List<RobotSpBean> updataSp;

    public static IProduct newProxyInstance() {
        return ProductHandler.product;
    }

    /**
     * 通过android 内部运行机制创建唯一的一个单例
     */
    public static class ProductHandler {
        static ProductProxy product = new ProductProxy();
    }

    private ProductProxy() {
        iProduct = new ProductImpl();
        if (ConfInfoUtil.getSN() != null) {
            SN = ConfInfoUtil.getSN();
            BlackgagaLogger.debug("获取 SN 成功，SN为：" + ConfInfoUtil.getSN());
        } else BlackgagaLogger.debug("获取 SN 失败，使用默认SN：12345678");
    }

    @Override
    public void getProductInfo(Observer<ProductInfo> observer) {
        iProduct.getProductInfo(observer);
    }

    public void getProductInfos(ProductListener listener) {
        ProductInfo productInfo = getLocalProduct();
        if (productInfo == null
                || productInfo.getResult() == null
                || productInfo.getResult().getProduct() == null
                || productInfo.getResult().getProduct().size() == 0) {
            getProductInfo(new Observer<ProductInfo>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull ProductInfo productInfo) {
                    saveProduct(productInfo, listener);
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });
        } else {
            listener.getProduct(productInfo);
        }
    }

    /**
     * 主动加载
     * 一级加载次加载列表数据
     * 包括主列表和产品列表
     */
    public void getRobotMenuList(MenuListListener listener) {
        RobotMenuListBean productInfo = getMenuList();
        if (ISUPDATA || productInfo == null) {
            //清楚所有缓存
            removeMenuList();
            removeSpList(Constants.Language.getLanguageStr());
            getRobotMenuList(SN, Constants.Language.getLanguageStr(), new Observer<RobotMenuListBean>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                }

                @Override
                public void onNext(@NonNull RobotMenuListBean robotMenuListBean) {
                    if (robotMenuListBean.getStatus().equals("500")) {
                        if (listener != null) {
                            listener.loadError500();
                        }
                    } else {
                        saveList(robotMenuListBean, listener, "");
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    if (listener != null) {
                        listener.onMenuError(e);
                        listener.onLocaleMenuList(getMenuList());
                    }
                }

                @Override
                public void onComplete() {

                }
            });
        } else if (!ISUPDATA && productInfo != null) {
            //本地如果有了数据就下载一下图片
            if (listener != null) {
                listener.getMenuList(productInfo);
            }
            downLoadMenuImage(productInfo, listener);
        }
    }


    /**
     * 主动加载
     * 根据类名下载和查找
     * 二级加载次加载列表数据
     * 包括主列表和产品列表
     */
    public synchronized void robotSpList(String menuid, Context context, SpListListener listener) {
        updataSp = new ArrayList<>();
        isLoadNum = 0;
        SP_SIZE = 0;
        RobotSpListBean productInfo = getSpList(menuid);
        //如果menuid == "" 那么就要重新下载数据并更新本地的
        if (ISUPDATA) {
            List<RobotMenuListBean.ResultBean.MenulistBean> list = getSpMenuList(context);
            removeMenuList();
            removeSpList(SharedKey.SP_LAN.getLanguageStr(Constants.Language.getLanguageStr()));
            NEED_LOAD = 0;
            NEED_LOAD_MEDIA = list.size();
            if (NEED_LOAD_MEDIA == 0) {
                if (listener != null)
                    listener.loadAllSuccess();
                return;
            }
            for (int i = 0; i < NEED_LOAD_MEDIA; i++) {
                getRobotSpListByUrl(list.get(i).getMURL().replace("{sn}", SN),
                        list.get(i).getMenuid(),
                        listener);
            }
        } else if (!ISUPDATA && !menuid.equals("")) {
            //获取当前的id
            String url = getOneSpURL(menuid);
            if (!url.equals("")) {
                getRobotSpListByUrl(url.replace("{sn}", SN),
                        menuid,
                        listener);
            }
        } else if (!menuid.equals("") && (!ISUPDATA && productInfo != null)) {
            //本地如果有了数据就下载图片
            downLoadSpImage(getSpList(menuid), listener);
            return;
        } else {
            return;
        }
    }

    /**
     * @param url            下载地址
     * @param menuid         导航id 为了利用id来保存数据
     * @param spListListener 状态监听
     */
    private synchronized void getRobotSpListByUrl(String url, String menuid, SpListListener spListListener) {
        fullDynamicGetRobotSpList(url, new Observer<RobotSpListBean>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
            }

            @Override
            public void onNext(@NonNull RobotSpListBean robotSpListBean) {
                BlackgagaLogger.debug("chenqi menuid = " + menuid + robotSpListBean.getStatus() );
                //接口返回下载的图片数量
                if (robotSpListBean.getStatus().equals("200")) {
                    RobotSpBean r = new RobotSpBean(robotSpListBean, menuid);
                    updataSp.add(r);
                }
                NEED_LOAD_MEDIA--;
                //确定需要下载的图片数量F
                if (NEED_LOAD_MEDIA <= 0) {
                    for (int i = 0; i < updataSp.size(); i++) {
                        getResQuantity(updataSp.get(i).getBean());
                    }
                    if (spListListener != null)
                        spListListener.ImageSize(SP_SIZE);
                    if (updataSp.size() != 0) {
                        for (int i = 0; i < updataSp.size(); i++) {
                            saveList(updataSp.get(i).getBean(), spListListener, updataSp.get(i).getMenuID());
                        }
                    } else {
                        if (spListListener != null)
                            spListListener.loadAllSuccess();
                    }
                    updataSp.clear();
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                if (spListListener != null) {
                    spListListener.onSpError(e);
                    spListListener.getSpList(getSpList(menuid));
                }
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 获取到所有sp子类下面的照片或者video
     *
     * @param robotSpListBean
     * @return
     */
    private int getResQuantity(RobotSpListBean robotSpListBean) {
        SP_SIZE = SP_SIZE + robotSpListBean.getResult().getProduct().size();
        for (int i = 0; i < robotSpListBean.getResult().getProduct().size(); i++) {
            SP_SIZE = SP_SIZE + robotSpListBean.getResult().getProduct().get(i).getViewUrl().size();
        }
        return SP_SIZE;
    }


    private void saveProduct(ProductInfo productInfo, ProductListener listener) {
        String data = new Gson().toJson(productInfo);
        // 将json字符串存入到本地
        if (SharedPreUtil.putString(SharedKey.PRODUCT_SP,
                SharedKey.PRODUCT_INFO, data)) {
            // 开始下载图片
            downLoadImage(productInfo, listener);
        }
    }

    /**
     * 两级下载的时候调用的方法
     *
     * @param bean
     * @param o
     * @param <T>
     */
    private <T> void saveList(T bean, T o, String menuid) {
        String data = new Gson().toJson(bean);
        if (bean instanceof RobotMenuListBean) {
            // 将json字符串存入到本地
            if (SharedPreUtil.putString(SharedKey.PRODUCT_MENU_LIST,
                    SharedKey.MENU_LAN.getLanguageStr(Constants.Language.getLanguageStr()), data)) {
                if (o != null) {
                    ((MenuListListener) o).getMenuList(getMenuList());
                }
                downLoadMenuImage((RobotMenuListBean) bean, (MenuListListener) o);
            }
        } else if (bean instanceof RobotSpListBean) {
            // 将json字符串存入到本地
            if (SharedPreUtil.putString(SharedKey.SP_LAN.getLanguageStr(Constants.Language.getLanguageStr()),
                    menuid, data)) {
                if (o != null) {
                    ((SpListListener) o).getSpList(getSpList(menuid));
                }
                downLoadSpImage((RobotSpListBean) bean, (SpListListener) o);
            }
        }
    }


    /**
     * 下载产品列表图片
     */
    private synchronized void downLoadSpImage(RobotSpListBean productInfo, SpListListener listener) {
        downloadCount = 0;
        alreadyCount = 0;
        List<RobotSpListBean.ResultBean.ProductBean> productList =
                productInfo.getResult().getProduct();
        if (productList == null) {
            BlackgagaLogger.debug(TAG + "下载图片数量不能为空！");
            return;
        }
        for (RobotSpListBean.ResultBean.ProductBean productBean : productList) {
            File pathFile = new File(PRODUCT_IMG_PATH);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            String imgName = productBean.getImgName();
            String toFilePath = PRODUCT_IMG_PATH + imgName;
            pathFile = new File(toFilePath);
            //检查本地数据是否已经存在了，如果没有存在就是用网络
            if (!ISUPDATA && pathFile.exists()) {
                isLoadNum++;
                alreadyCount++;
                int all = downloadCount + alreadyCount;
                downLoadSpViewContent(productBean, listener);
                listener.getSpList(productInfo);//判断是否产品页下载完毕
                if (listener != null && all < productList.size() && isLoadNum < SP_SIZE) {
                    listener.ImageLoadSuccess(imgName);//判断是否下载完毕
                } else if (listener != null && all >= productList.size() && isLoadNum >= SP_SIZE) {
                    listener.loadAllSuccess();//判断数据更新是否完成
                    isLoadNum = 0;
                }
                continue;
            }

            Glide.with(BaseApplication.getAppContext())
                    .asFile()
                    .load(productBean.getUrl())
                    .listener(new RequestListener<File>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
                            // 拷贝失败 第几张图失败了
                            if (listener != null)
                                listener.ImageLoadFailed(imgName);
                            downloadCount++;
                            isLoadNum++;
                            //下载这列中的view
                            int all = downloadCount + alreadyCount;
                            downLoadSpViewContent(productBean, listener);
                            listener.getSpList(productInfo);
                            if (NEED_LOAD == 0 && listener != null && all < productList.size() && isLoadNum < SP_SIZE) {
                                listener.ImageLoadSuccess(imgName);
                            } else if (NEED_LOAD == 0 && listener != null && all == productList.size() && isLoadNum >= SP_SIZE) {
                                listener.loadAllSuccess();
                                isLoadNum = 0;
                            }
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .into(new SimpleTarget<File>() {
                        @Override
                        public void onResourceReady(File resource, Transition<? super File> transition) {
                            Observable.just(FileUtil.copy(resource, new File(toFilePath)))
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(b -> {
                                        if (b) {
                                            if (listener != null)
                                                listener.ImageLoadSuccess(imgName);
                                            // 拷贝成功 第几张图
                                        } else {
                                            if (listener != null) {
                                                listener.ImageLoadFailed(imgName);
                                            }
                                        }
                                        isLoadNum++;
                                        downloadCount++;
                                        downLoadSpViewContent(productBean, listener);
                                        listener.getSpList(productInfo);
                                        int all = downloadCount + alreadyCount;
                                        if (NEED_LOAD == 0 && listener != null && all < productList.size() && isLoadNum < SP_SIZE) {
                                            listener.ImageLoadSuccess(imgName);
                                        } else if (NEED_LOAD == 0 && listener != null && all == productList.size() && isLoadNum >= SP_SIZE) {
                                            listener.loadAllSuccess();
                                        }
                                    }, e -> {
                                        Csjlogger.error(e);
                                        if (listener != null) {
                                            listener.cacheToMore();
                                        }
//                                        downLoadSpImage(productInfo, listener);
                                        // 可能引发错误的原因是什么呢？
                                        // 1.内存不足
                                        // 2.io异常
                                        // 3.文件地址错误
                                        // 4.网络错误
                                    });
                        }
                    });
        }

    }

    /**
     * 下载导航列表图片
     * 下载导航列表的时候把产品列表也更新掉
     */
    private synchronized void downLoadMenuImage(RobotMenuListBean productInfo, MenuListListener listener) {
        ARLEADY_DOWNLOAD = 0;
        downloadCount = 0;
        alreadyCount = 0;
        List<RobotMenuListBean.ResultBean.MenulistBean> productList =
                productInfo.getResult().getMenulist();
        if (productList == null || productList.size() == 0) {
            BlackgagaLogger.debug("下载图片数量不能为空！");
            return;
        }
        if (listener != null) {
            listener.ImageSize(productList.size());
        }

        for (RobotMenuListBean.ResultBean.MenulistBean productBean : productList) {
            File pathFile = new File(PRODUCT_IMG_PATH);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            String imgName = getMenuImageName(productBean.getMImg());
            String toFilePath = PRODUCT_IMG_PATH + imgName;
            pathFile = new File(toFilePath);
            //检查本地数据是否已经存在了，如果没有存在就是用网络
            if (!ISUPDATA && pathFile.exists()) {
                alreadyCount++;
                ARLEADY_DOWNLOAD = downloadCount + alreadyCount;
                // 拷贝成功
                if (listener != null) {
                    listener.ImageLoadSuccess(imgName);
                }
                if (ARLEADY_DOWNLOAD >= productList.size()) {
                    if (listener != null) {
                        listener.loadAllSuccess();
                    }
                }
                continue;
            }
            Glide.with(BaseApplication.getAppContext())
                    .asFile()
                    .load(productBean.getMImg())
                    .listener(new RequestListener<File>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
                            // 拷贝失败
                            if (listener != null) {
                                listener.ImageLoadFailed(imgName);
                            }
                            downloadCount++;
                            ARLEADY_DOWNLOAD = downloadCount + alreadyCount;
                            if (ARLEADY_DOWNLOAD >= productList.size()) {
                                if (listener != null) {
                                    listener.loadAllSuccess();
                                }
                            }
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .into(new SimpleTarget<File>() {
                        @Override
                        public void onResourceReady(File resource, Transition<? super File> transition) {
                            Observable.just(FileUtil.copy(resource, new File(toFilePath)))
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(b -> {
                                        if (b) {
                                            // 拷贝成功
                                            if (listener != null) {
                                                listener.ImageLoadSuccess(imgName);
                                            }
                                        } else {
                                            // 拷贝成功
                                            if (listener != null) {
                                                listener.ImageLoadFailed(imgName);
                                            }
                                        }
                                        downloadCount++;
                                        ARLEADY_DOWNLOAD = downloadCount + alreadyCount;
                                        if (ARLEADY_DOWNLOAD >= productList.size()) {
                                            if (listener != null) {
                                                listener.loadAllSuccess();
                                            }
                                        }
                                    }, e -> {
                                        e.printStackTrace();
                                        if (listener != null) {
                                            listener.cacheToMore();
                                        }
                                        // 可能引发错误的原因是什么呢？
                                        // 1.内存不足
                                        // 2.io异常
                                        // 3.文件地址错误
                                    });
                        }
                    });
        }
    }

    /**
     * 下载图片的名字
     * @param url
     * @return
     */
    public static String getMenuImageName(String url) {
        if (!url.equals("") && url != null) {
            String[] ss = url.split("/");
            for (int i = 0; i < ss.length; i++) {
                if ((i + 1) == ss.length) {
                    return ss[i];
                }
            }
        }
        return "";
    }

    /**
     * 下载产品明细中轮播图片或者视频资源
     */
    private synchronized void downLoadSpViewContent(RobotSpListBean.ResultBean.ProductBean productInfo, SpListListener listener) {
        if (productInfo == null || productInfo.getViewUrl().size() == 0) {
            BlackgagaLogger.debug(TAG + "下载轮播图片或者视频资源数量不能为空！");
            return;
        }
        if (productInfo.getViewType() == 2) {//轮播图片
            List<String> imageLists = productInfo.getViewUrl();
            downLoadLoopViewContent(imageLists, listener);
        } else if (productInfo.getViewType() == 1) {//视频资源
            downLoadVideoViewContent(productInfo.getViewUrl().get(0), listener);
        }
    }


    /**
     * 下载轮播图片
     */
    private synchronized void downLoadLoopViewContent(List<String> imageList, SpListListener listener) {
        File pathFile = new File(Constants.PRODUCT_IMG_PATH);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        for (String imageName : imageList) {
            String imgName = FileUtil.getFileName(imageName);
            String filepath = Constants.PRODUCT_IMG_PATH + imgName;
            File file = new File(filepath);
            if (!ISUPDATA && file.exists()) {
                isLoadNum++;
                if (listener != null)
                    listener.ImageLoadSuccess(imageName);
                if (listener != null && isLoadNum >= SP_SIZE) {
                    listener.loadAllSuccess();
                }
                continue;
            }
            Glide.with(BaseApplication.getAppContext())
                    .asFile()
                    .load(imageName)
                    .listener(new RequestListener<File>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
                            isLoadNum++;
                            if (listener != null)
                                listener.ImageLoadFailed(imageName);
                            if (listener != null && isLoadNum >= SP_SIZE) {
                                listener.loadAllSuccess();
                            }
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .into(new SimpleTarget<File>() {
                        @Override
                        public void onResourceReady(File resource, Transition<? super File> transition) {
                            Observable.just(FileUtil.copy(resource, new File(filepath)))
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(b -> {
                                        if (b) {
                                            if (listener != null)
                                                listener.ImageLoadSuccess(imageName);
                                        } else {
                                            if (listener != null)
                                                listener.ImageLoadFailed(imageName);
                                        }
                                        isLoadNum++;
                                        BlackgagaLogger.debug(TAG + "图片下载成功 这个是在几类中  " + isLoadNum + "一共要下载" + SP_SIZE);
                                        if (listener != null && isLoadNum >= SP_SIZE) {
                                            BlackgagaLogger.debug(TAG + "全部已经下载了 这个是在几类中下载完成的  " + isLoadNum + "一共要下载" + SP_SIZE);
                                            listener.loadAllSuccess();
                                        }
                                    }, e -> {
                                        if (listener != null) {
                                            listener.cacheToMore();
                                        }
                                        BlackgagaLogger.error(e);
                                    });
                        }
                    });
        }
    }

    /**
     * 下载视频资源
     */
    private synchronized void downLoadVideoViewContent(String videoUrl, SpListListener listener) {
        File pathFile = new File(Constants.PRODUCT_VIDEO_PATH);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        String videoName = FileUtil.getFileName(videoUrl);
        String videopath = Constants.PRODUCT_VIDEO_PATH + videoName;
        File file = new File(videopath);
        if (!ISUPDATA && file.exists()) {
            isLoadNum++;
            if (listener != null)
                listener.ImageLoadSuccess(videoName);
            if (listener != null && isLoadNum >= SP_SIZE) {
                BlackgagaLogger.debug(TAG + "全部已经下载了video 1  " + isLoadNum + "一共要下载" + SP_SIZE);
                listener.loadAllSuccess();
            }
            BlackgagaLogger.debug(TAG + "已经下载了video 1 " + isLoadNum + "一共要下载" + SP_SIZE);
            return;
        }
        Glide.with(BaseApplication.getAppContext())
                .asFile()
                .load(videoUrl)
                .listener(new RequestListener<File>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
                        isLoadNum++;
                        if (listener != null) {
                            if (isLoadNum >= SP_SIZE) {
                                listener.loadAllSuccess();
                                isLoadNum = 0;
                            } else
                                listener.ImageLoadFailed(videoName);
                        }
                        BlackgagaLogger.debug(TAG + "视频下载失败 这个是在几类中  " + isLoadNum + "一共要下载" + SP_SIZE);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                })
                .into(new SimpleTarget<File>() {
                    @Override
                    public void onResourceReady(File resource, Transition<? super File> transition) {
                        Observable.just(FileUtil.copy(resource, new File(videopath)))
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(b -> {
                                    if (b) {
                                        if (listener != null)
                                            listener.ImageLoadSuccess(videoName);
                                        BlackgagaLogger.debug(TAG + "下载并拷贝成功：" + videoUrl);
                                    } else {
                                        if (listener != null)
                                            listener.ImageLoadFailed(videoName);
                                        BlackgagaLogger.debug(TAG + "下载并拷贝失败：" + videoUrl);
                                    }
                                    isLoadNum++;
                                    BlackgagaLogger.debug(TAG + "视频下载成功 这个是在几类中  " + isLoadNum + "一共要下载" + SP_SIZE);
                                    if (listener != null && isLoadNum >= SP_SIZE) {
                                        BlackgagaLogger.debug(TAG + "全部已经下载了video 2  " + isLoadNum + "一共要下载" + SP_SIZE);
                                        listener.loadAllSuccess();
                                    }
                                }, e -> {
                                    if (listener != null) {
                                        listener.cacheToMore();
                                    }
                                    BlackgagaLogger.error(e);
                                });
                    }
                });
    }


    @Override
    public RobotSpListBean getSpList(String menuid) {
        return iProduct.getSpList(menuid);
    }

    @Override
    public boolean removeSpList(String lan) {
        return iProduct.removeSpList(lan);
    }

    @Override
    public boolean removeMenuList() {
        return iProduct.removeMenuList();
    }


    /**
     * 开启应用加载
     * 一级加载次加载列表数据
     * 包括主列表和产品列表
     */
    public void getRobotMenuList(boolean b) {
        ISUPDATA = b;
        getRobotMenuList(SN, Constants.Language.getLanguageStr(), new Observer<RobotMenuListBean>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
            }

            @Override
            public void onNext(@NonNull RobotMenuListBean robotMenuListBean) {
                Log.e("chenqi menu", robotMenuListBean + "");
                saveList(robotMenuListBean, null, "");
            }

            @Override
            public void onError(@NonNull Throwable e) {
                BlackgagaLogger.debug(" getRobotMenuList 服务器炸了 " + e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 下载图片
     */
    private void downLoadImage(ProductInfo productInfo, ProductListener listener) {
        List<ProductInfo.ResultBean.ProductBean> productList = productInfo.getResult().getProduct();
        if (productList == null || productList.size() == 0) {
            BlackgagaLogger.debug("下载图片数量不能为空！");
            return;
        }

        int count = 1;
        File pathFile = new File(Constants.PRODUCT_IMG_PATH);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        for (ProductInfo.ResultBean.ProductBean productBean : productList) {
            String imgName = productBean.getImgName();
            String toFilePath = Constants.PRODUCT_IMG_PATH + File.separator + imgName;
            File file = new File(toFilePath);
            if (file.exists()) {
                downloadCount++;
                if (downloadCount == productList.size()) {
                    if (listener != null) {
                        listener.getProduct(productInfo);
                    }
                    BlackgagaLogger.debug("拷贝全部成功：" + productBean.getImgName());
                } else {
                    continue;
                }
            }
            BlackgagaLogger.debug("第 " + count + " 张图片开始下载：" + productBean.getUrl());
            Glide.with(BaseApplication.getAppContext())
                    .asFile()
                    .load("http://" + productBean.getUrl())
                    .into(new SimpleTarget<File>() {
                        @Override
                        public void onResourceReady(File resource, Transition<? super File> transition) {
                            BlackgagaLogger.debug("拷贝路径：" + toFilePath);
                            Observable.just(FileUtil.copy(resource, new File(toFilePath)))
                                    .subscribeOn(Schedulers.io())
                                    .observeOn(AndroidSchedulers.mainThread())
                                    .subscribe(b -> {
                                        if (b) {
                                            // 拷贝成功
                                            BlackgagaLogger.debug("下载并拷贝成功：" + productBean.getImgName());
                                        } else {
                                            // 拷贝失败
                                            BlackgagaLogger.debug("拷贝失败：" + productBean.getImgName());
                                        }
                                        downloadCount++;
                                        if (downloadCount == productList.size()) {
                                            if (listener != null) {
                                                listener.getProduct(productInfo);
                                            }
                                            BlackgagaLogger.debug("拷贝全部成功：" + productBean.getImgName());
                                        }

                                    }, e -> {
                                        BlackgagaLogger.error(e);
                                        // 可能引发错误的原因是什么呢？
                                        // 1.内存不足
                                        // 2.io异常

                                    });
                        }
                    });
            count++;
        }
    }

    public String getOneSpURL(String menuid) {
        String spUrl = "";
        if (getMenuList() != null) {
            for (RobotMenuListBean.ResultBean.MenulistBean d : getMenuList().getResult().getMenulist()) {
                if (menuid.equals(d.getMenuid())) {
                    spUrl = d.getMURL();
                }
            }
        }
        return spUrl;
    }

    public List<RobotMenuListBean.ResultBean.MenulistBean> getSpMenuList(Context context) {
        List<RobotMenuListBean.ResultBean.MenulistBean> list = new ArrayList<>();
        String spId = "";
        if (getMenuList() != null) {
            for (RobotMenuListBean.ResultBean.MenulistBean d : getMenuList().getResult().getMenulist()) {
                if (context.getResources().getString(R.string.product).equals(d.getMenuName())) {
                    spId = d.getMenuid();
                    break;
                }
            }

            for (int i = 0; i < getMenuList().getResult().getMenulist().size(); i++) {
                if (spId.equals(getMenuList().getResult().getMenulist().get(i).getParentid())) {
                    list.add(getMenuList().getResult().getMenulist().get(i));
                }
            }
        }
        return list;
    }

    @Override
    public ProductInfo getLocalProduct() {
        return iProduct.getLocalProduct();
    }

    @Override
    public RobotMenuListBean getMenuList() {
        return iProduct.getMenuList();
    }

    @Override
    public void getAdInfo(Observer<AdInfo> observer) {
        iProduct.getAdInfo(observer);
    }

    @Override
    public void generateOrder(String json, Observer<PayResponse> observer) {
        iProduct.generateOrder(json, observer);
    }

    @Override
    public void sendEvalution(String json, Observer<AnswerResponse> observer) {
        iProduct.sendEvalution(json, observer);
    }

    public void sendEvalution(String json, EvalutionListener listener) {
        sendEvalution(json, new Observer<AnswerResponse>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {
            }

            @Override
            public void onNext(@NonNull AnswerResponse evaluationAnswer) {
                if (evaluationAnswer.getStatus().equals("200")) {
                    listener.sendEvalutionSuccess();
                } else if (evaluationAnswer.getStatus().equals("500")) {
                    listener.sendEvalutionFailed();
                }
            }

            @Override
            public void onError(@NonNull Throwable e) {
                listener.sendEvalutionFailed();
            }

            @Override
            public void onComplete() {
            }
        });
    }

    public void generateOrder(String json, OrderCodeUrlListener listener) {
        generateOrder(json, new Observer<PayResponse>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull PayResponse payResponse) {
                listener.getOrderCodeUrl(payResponse);
            }

            @Override
            public void onError(@NonNull Throwable e) {
                listener.onOrderCodeError();
            }

            @Override
            public void onComplete() {
                listener.onOrderCodeComplete();
            }
        });
    }

    @Override
    public void searchPayResult(String orderid, Observer<PayResult> observer) {
        iProduct.searchPayResult(orderid, observer);
    }

    @Override
    public void getRobotMenuList(String sn, String language, Observer<RobotMenuListBean> observer) {
        iProduct.getRobotMenuList(sn, language, observer);
    }

    @Override
    public void dynamicGetRobotSpList(String url, String sn, Observer<RobotSpListBean> observer) {
        iProduct.dynamicGetRobotSpList(url, sn, observer);
    }

    @Override
    public void fullDynamicGetRobotSpList(String url, Observer<RobotSpListBean> observer) {
        iProduct.fullDynamicGetRobotSpList(url, observer);
    }

    @Override
    public void getProductImage(String url, Observer<ResponseBody> observer) {
        iProduct.getProductImage(url, observer);
    }

    public interface ProductListener {
        void getProduct(ProductInfo productInfo);
    }

    public interface MenuListListener extends LoadImageListener {
        void getMenuList(RobotMenuListBean bean);

        void onMenuError(Throwable e);

        void onLocaleMenuList(RobotMenuListBean bean);

        void ImageSize(int num);
    }

    public interface SpListListener extends LoadImageListener {
        void getSpList(RobotSpListBean bean);

        void onSpError(Throwable e);

        void onLocaleSpList(RobotSpListBean bean);

        void ImageSize(int num);


    }

    public interface OrderCodeUrlListener {
        void getOrderCodeUrl(PayResponse payResponse);

        void onOrderCodeError();

        void onOrderCodeComplete();
    }

    public interface EvalutionListener {
        void sendEvalutionSuccess();

        void sendEvalutionFailed();
    }
}
